﻿using DevExpress.XtraEditors;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace MachineBuildingSystem
{
    public partial class OrderManageForm : XtraForm
    {
        private string m_CurrentUser = "";
        private string m_Password = "";
        //操作权限
        private List<long> m_ActionList = new List<long>();
        private BaseDataInfo m_BaseDataInfo = null;
        private BackgroundWorker m_BackgroundWorker = null;

        List<MaterialInfo> m_MaterialInfoList = new List<MaterialInfo>();


        public OrderManageForm(string currentUser, string password, List<long> actionList, string employeeName)
        {
            m_CurrentUser = currentUser;
            m_Password = password;
            m_ActionList = actionList;
            InitializeComponent();
            barStaticItemCurrentUser.Caption = employeeName;
        }

        private void OrderAddForm_Load(object sender, EventArgs e)
        {
            string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            this.Text += "(" + version + ")";
            if (m_ActionList.Contains((int)ActionEnum.Action) || m_CurrentUser == "system")
                this.bar1.Visible = true; 
            else
                this.bar1.Visible = false;
            this.Size = Screen.GetWorkingArea(this).Size;
            this.Location = new Point(0, 0);
            this.orderShowInfo.OrderEvent += orderShowUC_OrderEvent;
            this.orderAddUC.OrderAddSuccessEvent += orderAddUC_OrderAddSuccessEvent;
            this.orderAddUC.myReturnEvent += orderAddUC_myReturnEvent;
            this.orderAddUC.RefreshEvent += orderAddUC_RefreshEvent;
            this.orderSend.sendReturnEvent += orderSend_sendReturnEvent;

            m_BackgroundWorker = new BackgroundWorker();
            m_BackgroundWorker.WorkerReportsProgress = true;
            m_BackgroundWorker.WorkerSupportsCancellation = true;
            m_BackgroundWorker.DoWork += m_BackgroundWorker_DoWork;
            m_BackgroundWorker.RunWorkerCompleted += m_BackgroundWorker_RunWorkerCompleted;
            this.orderShowInfo.SetProgress(true);
            m_BackgroundWorker.RunWorkerAsync();
        }

        void m_BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                LogHelper.error("初始化基础数据出现异常：" + e.Error.Message);
                MessageBox.Show(this, e.Error.Message);
                return;
            }
            this.orderShowInfo.SetProgress(false);
            m_BaseDataInfo = e.Result as BaseDataInfo;
            if (m_BaseDataInfo == null)
                return;
            this.orderShowInfo.InitOrderShowUC(m_CurrentUser, m_Password, m_ActionList, m_BaseDataInfo.CustomerInfoList, m_BaseDataInfo.MaterialInfoList);
            this.orderShowInfo.RefreshOrder();
            int refreshFormulaTime = int.Parse(ConfigurationManager.AppSettings["RefreshFormulaTime"]);
            if (m_ActionList.Contains((int)ActionEnum.Formula))
            {
                timerRefresh.Interval = refreshFormulaTime * 1000;
                timerRefresh.Enabled = true;
            }
        }

        void m_BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //初始化一些基础数据
            BaseDataInfo info = new BaseDataInfo();
            try
            {
                List<CustomerInfo> customerInfoList = InitCustomerData();
                List<MaterialInfo> materialInfoList = InitMaterialData();
                m_MaterialInfoList = materialInfoList;
                //List<ProjectInfo> projectInfoList = InitProjectData();
                List<SlumpInfo> slumpInfoInfoList = InitSlumpData();
                //List<ZoneInfo> zoneInfoList = InitZoneData();
                //List<ConstructSiteInfo> constructSiteInfoList = InitConstructSiteData();
                List<TransportInfo> transportInfoList = InitTransportData();

                info.CustomerInfoList = customerInfoList;
                info.MaterialInfoList = materialInfoList;
                //info.ProjectInfoList = projectInfoList;
                info.SlumpInfoInfoList = slumpInfoInfoList;
                //info.ZoneInfoList = zoneInfoList;
                //info.ConstructSiteInfoList = constructSiteInfoList;
                info.TransportInfoList = transportInfoList;
            }
            catch
            {
                throw;
            }
            e.Result = info;
        }

        #region 初始化基础数据
        //初始化客户
        private List<CustomerInfo> InitCustomerData()
        {
            List<CustomerInfo> customerInfoList = null;
            try
            {
                customerInfoList = DataHelper.GetCustomers(m_CurrentUser, m_Password, 0, "", "");
            }
            catch
            {
                throw;
            }
            return customerInfoList;
        }

        //初始化物料
        private List<MaterialInfo> InitMaterialData()
        {
            List<MaterialInfo> materialInfoList = null;
            try
            {
                materialInfoList = DataHelper.GetMaterials(m_CurrentUser, m_Password);
            }
            catch
            {
                throw;
            }
            return materialInfoList;
        }

        //工程名称
        private List<ProjectInfo> InitProjectData()
        {
            List<ProjectInfo> projectInfoList = null;
            try
            {
                projectInfoList = DataHelper.GetProjectInfo(m_CurrentUser, m_Password, "null");
            }
            catch
            {
                throw;
            }
            return projectInfoList;
        }

        //施工部位
        private List<ConstructSiteInfo> InitConstructSiteData()
        {
            List<ConstructSiteInfo> constructSiteInfoList = null;
            try
            {
                constructSiteInfoList = DataHelper.GetConstructSiteInfo(m_CurrentUser, m_Password);
            }
            catch
            {
                throw;
            }
            return constructSiteInfoList;
        }

        //输送方式
        private List<TransportInfo> InitTransportData()
        {
            List<TransportInfo> transportInfoList = null;
            try
            {
                transportInfoList = DataHelper.GetTransportInfo(m_CurrentUser, m_Password);
            }
            catch
            {
                throw;
            }
            return transportInfoList;
        }

        //坍落度要求
        private List<SlumpInfo> InitSlumpData()
        {
            List<SlumpInfo> slumptInfoList = null;
            try
            {
                slumptInfoList = DataHelper.GetSlumpInfo(m_CurrentUser, m_Password, "null");
            }
            catch
            {
                throw;
            }
            return slumptInfoList;
        }

        //区域
        private List<ZoneInfo> InitZoneData()
        {
            List<ZoneInfo> zoneInfoList = null;
            try
            {
                int belongcorpId = int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]);
                zoneInfoList = DataHelper.GetZoneInfo(m_CurrentUser, m_Password, belongcorpId);
            }
            catch
            {
                throw;
            }
            return zoneInfoList;
        }
        #endregion

        //新增订单成功后关闭订单新增界面并刷新订单列表
        void orderAddUC_OrderAddSuccessEvent(object sender, EventArgs e)
        {
            this.pageOrderDetail.PageVisible = false;
            this.tabControlOrder.SelectedTabPageIndex = 0;
            this.orderShowInfo.RefreshOrder();
        }
        void orderAddUC_RefreshEvent(object sender, EventArgs e)
        {
            this.orderShowInfo.RefreshOrder();
        }

        void orderAddUC_myReturnEvent(object sender, EventArgs e)
        {
            this.pageOrderDetail.PageVisible = false;
            this.tabControlOrder.SelectedTabPageIndex = 0;
            this.orderShowInfo.RefreshOrder();
        }

        void orderSend_sendReturnEvent(object sender, EventArgs e)
        {
            this.pageOrderSend.PageVisible = false;
            this.tabControlOrder.SelectedTabPageIndex = 0;
            this.orderShowInfo.RefreshOrder();
        }

        void orderShowUC_OrderEvent(object sender, OrderArgument e)
        {
            OrderTypeEnum type = e.Type;
            OrderInfo order = e.OrderInfo as OrderInfo;
            if (type == OrderTypeEnum.OrderAdd)
            {
                this.pageOrderDetail.Text = "新增订单";
                this.orderAddUC.RefreshOrder(m_CurrentUser, m_Password, m_ActionList, type, m_BaseDataInfo, order);
                this.pageOrderDetail.PageVisible = true;
                this.tabControlOrder.SelectedTabPageIndex = 1;
            }
            else if (type == OrderTypeEnum.OrderUpdate || type == OrderTypeEnum.OrderUpdateByAudited)
            {
                this.pageOrderDetail.Text = "修改订单";
                this.orderAddUC.RefreshOrder(m_CurrentUser, m_Password, m_ActionList, type, m_BaseDataInfo, order);
                this.pageOrderDetail.PageVisible = true;
                this.tabControlOrder.SelectedTabPageIndex = 1;
            }
            else if (type == OrderTypeEnum.OrderDetail)
            {
                this.pageOrderDetail.Text = "订单详情";
                this.orderAddUC.RefreshOrder(m_CurrentUser, m_Password, m_ActionList, type, m_BaseDataInfo, order);
                this.pageOrderDetail.PageVisible = true;
                this.tabControlOrder.SelectedTabPageIndex = 1;
            }
            else if (type == OrderTypeEnum.DeliveryAdd)
            {
                this.pageOrderSend.Text = "发货新增";
                this.orderSend.RefreshOrderSendInfo(m_CurrentUser, m_Password, m_ActionList, true, order);
                this.pageOrderSend.PageVisible = true;
                this.tabControlOrder.SelectedTabPageIndex = 2;
            }
            else if (type == OrderTypeEnum.DeliveryDetail)
            {
                this.pageOrderSend.Text = "发货详情";
                this.orderSend.RefreshOrderSendInfo(m_CurrentUser, m_Password, m_ActionList, false, order);
                this.pageOrderSend.PageVisible = true;
                this.tabControlOrder.SelectedTabPageIndex = 2;
            }
        }

        //定时刷新未执行实施配配比的订单，并右下角弹框
        private void timerRefresh_Tick(object sender, EventArgs e)
        {
            ParameterizedThreadStart parameter = new ParameterizedThreadStart(DoShowInfoHandler);
            Thread myThread = new Thread(parameter);
            myThread.Start();
        }

        public delegate void ShowSuspendDelegate(List<FormulasStatusInfo> list);
        private void DoShowInfoHandler(object obj)
        {
            List<FormulasStatusInfo> list = new List<FormulasStatusInfo>();
            try
            {
                //获取未执行的实施配比
                list = DataHelper.GetFormulasStatusInfoList(m_CurrentUser, m_Password);
                if (list == null || list.Count == 0)
                    return;
            }
            catch(Exception ex)
            {
                LogHelper.error("定时刷新未执行实施配配比的订单异常：" + ex.ToString());
                return;
            }
            ////弹出提示框
            //HaveNewFormulaInfo form = new HaveNewFormulaInfo();//Form1为要弹出的窗体（提示框），  
            //form.OnSaleFormulasByStatus_Event += form_OnSaleFormulasByStatus_Event;
            //form.FormulasStatusInfoList = list;
            //Point p = new Point(Screen.PrimaryScreen.WorkingArea.Width - form.Width, Screen.PrimaryScreen.WorkingArea.Height);
            //form.PointToScreen(p);
            //form.Location = p;
            //form.BringToFront();
            //form.Show(this.Parent);
            //for (int i = 0; i <= form.Height; i++)
            //{
            //    form.Location = new Point(p.X, p.Y - i);
            //    Thread.Sleep(10);//将线程沉睡时间调的越小升起的越快  
            //}

            ShowSuspendDelegate mi = new ShowSuspendDelegate(DoShowInfo);
            BeginInvoke(mi, new object[] { list });
        }

        private void DoShowInfo(List<FormulasStatusInfo> list)
        {
            try
            {
                //弹出提示框
                HaveNewFormulaInfo form = new HaveNewFormulaInfo();//Form1为要弹出的窗体（提示框），  
                form.OnSaleFormulasByStatus_Event += form_OnSaleFormulasByStatus_Event;
                form.FormulasStatusInfoList = list;
                Point p = new Point(Screen.PrimaryScreen.WorkingArea.Width - form.Width, Screen.PrimaryScreen.WorkingArea.Height);
                form.PointToScreen(p);
                form.Location = p;
                form.BringToFront();
                form.Show(this.Parent);
                for (int i = 0; i <= form.Height; i++)
                {
                    form.Location = new Point(p.X, p.Y - i);
                    Thread.Sleep(5);//将线程沉睡时间调的越小升起的越快  
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("弹框提示未执行的实施配比异常:" + ex.ToString());
            }
        }

        void form_OnSaleFormulasByStatus_Event(object sender, FormulasStatusEventArgs e)
        {
            List<OrderInfo> orderInfoList = new List<OrderInfo>();
            try
            {
                long orderId = Convert.ToInt64(e.OrderId);
                //根据订单Id获取订单信息
                string types = ((int)ExecuteStatusEnum.EXECUTE).ToString() + ":" + ((int)ExecuteStatusEnum.UN_EXECUTE).ToString()
                     + ":" + ((int)ExecuteStatusEnum.PAUSE).ToString() + ":" + ((int)ExecuteStatusEnum.CLOSE).ToString();
                string audites = "0:1";
                int belongcorpId = int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]);
                orderInfoList = DataHelper.GetSaleOrders(m_CurrentUser, m_Password, belongcorpId,
                    orderId, "", 0, 0, DateTime.MinValue, DateTime.MaxValue, types, audites, 0, 50);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
                return;
            }
            if (orderInfoList == null || orderInfoList.Count == 0)
                return;
            OrderArgument argument = new OrderArgument(OrderTypeEnum.OrderDetail, orderInfoList[0]);
            orderShowUC_OrderEvent(this, argument);
 
        }

        private void OrderManageForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
            if (System.Diagnostics.Process.GetCurrentProcess() != null)
                System.Diagnostics.Process.GetCurrentProcess().Kill(); 
        }

        private void OrderManageForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否确认关闭", "提示", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                e.Cancel = true;
            }
        }

        private void barUserCfg_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            UserMgr form = new UserMgr();
            form.CurrentUser = m_CurrentUser;
            form.Password = m_Password;
            form.ShowDialog();
        }

        private void barRoleCfg_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RoleMgr form = new RoleMgr();
            form.ShowDialog();
        }

        private void barActionCfg_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ActionMgr form = new ActionMgr();
            form.ShowDialog();
        }

        private void btnDB2Cfg_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DB2CfgForm form = new DB2CfgForm();
            form.ShowDialog();
        }

        private void btnSqlCfg_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SqlCfgForm form = new SqlCfgForm();
            form.ShowDialog();
        }

        //司机车牌号维护
        private void barDriverCarCfg_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DriverCarCfgForm form = new DriverCarCfgForm();
            form.ShowDialog();
        }

        private void barStrengthGrade_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            StrengthGradeFormCfg form = new StrengthGradeFormCfg();
            form.ShowDialog();
        }

        //物料对照
        private void barMaterialCross_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MaterialCrossForm form = new MaterialCrossForm();
            form.MaterialInfoList = m_MaterialInfoList;
            form.ShowDialog();
        }

        private void barIntegrationCfg_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            IntegrationCfgForm form = new IntegrationCfgForm();
            form.ShowDialog();
        }
    }
}
